﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using Songhay.Data.GenericWeb.Properties;
using System.Xml.XPath;
using System.IO;
using System.Xml;
using System.Text;

namespace Songhay.Data.GenericWeb.Procedure
{
    internal static partial class Get
    {
        internal static XPathDocument SegmentForEdit(DbConnection commonConnection, string uniqueIdentifier)
        {
            if(commonConnection == null) throw new ArgumentNullException("commonConnection", "The Common Connection is null.");
            if(uniqueIdentifier == null) throw new ArgumentNullException("uniqueIdentifier", "The unique identifer is null.");

            Dictionary<String, Object> paramSet = new Dictionary<string, object>(2);
            paramSet.Add("@SegmentId", uniqueIdentifier);
            paramSet.Add("@GlobalDateFormat", CommandHandler.GlobalDateFormat);

            string segmentInnerXml = Common.CommonScalar.GetString(commonConnection, Resources.GetSegmentForEdit, paramSet);
            if(segmentInnerXml == null) throw new DataException(String.Format("Segment {0} was not found.", uniqueIdentifier));

            string childDocuments = Common.CommonScalar.GetString(commonConnection, Resources.ListChildDocuments, paramSet);
            string childFragments = Common.CommonScalar.GetString(commonConnection, Resources.ListChildFragments, paramSet);
            string childSegments = Common.CommonScalar.GetString(commonConnection, Resources.ListChildSegments, paramSet);

            paramSet = new Dictionary<string, object>(1);
            paramSet.Add("@SegmentId", uniqueIdentifier);

            string segments = List.Segments(commonConnection);

            XPathDocument d = null;
            using(MemoryStream stream = new MemoryStream())
            {
                using(XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8))
                {
                    writer.WriteStartDocument();
                    writer.WriteStartElement("ServerData");

                    writer.WriteRaw(segmentInnerXml);

                    writer.WriteStartElement("SubSets");

                    writer.WriteRaw(segments);
                    writer.WriteRaw(childSegments);
                    writer.WriteRaw(childDocuments);
                    writer.WriteRaw(childFragments);

                    writer.WriteFullEndElement();

                    writer.WriteFullEndElement();
                    writer.WriteEndDocument();

                    writer.Flush();

                    stream.Position = 0;
                    d = new XPathDocument(stream);
                }
            }

            return d;
        }
    }
}
